package wjh.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import wjh.pojo.Department;
import wjh.service.wyDepartmentService;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServlet;
import java.util.List;

@Controller
@RequestMapping("/departmentList")
public class wyDepartmentController extends HttpServlet {
    @Autowired
    private wyDepartmentService departmentService;
    @Qualifier("httpServletRequest")
    @Autowired
    private ServletRequest httpServletRequest;

    @RequestMapping("/findAll")
    public String findAll(

            @RequestParam(required = false,defaultValue ="1")Integer pageNum,
            @RequestParam(required = false,defaultValue ="3")Integer pageSize,
            String likename, Model model
    ){
        PageHelper.startPage(pageNum,pageSize);
        List<Department> DepartmentList= departmentService.like(likename);
        PageInfo<Department> pageInfo = new PageInfo<>(DepartmentList);
        model.addAttribute("page",pageInfo);
        model.addAttribute("likename",likename);
        return "departmentList";
    }
    @RequestMapping("/addDepartment")
    public String addUser(Department department) {

        departmentService.addDepartment(department);
        return "redirect:/departmentList/findAll.do";


    }

@RequestMapping("/del")
public ResponseEntity<String> deleteRegisters(@RequestParam String ids) {
    try {
        departmentService.deleteDepartmentByid(ids);
        return ResponseEntity.ok("删除成功");
    } catch (Exception e) {
        // 记录异常并返回错误信息
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("删除失败");
    }
}

@RequestMapping("/findDepartmentById")
public String findDepartmentById(@RequestParam("id") String id, Model model) {
    Department department=departmentService.findDepartmentById (Integer.parseInt(id));
    model.addAttribute("department",department);
    return "updateDepartment";
}
@RequestMapping("/updateDepartment")
public String updateDepartment(Department department,Model model) {
        departmentService.updateDepartment(department);
        int id=department.getId();
        model.addAttribute("id",id);
        model.addAttribute("department",department);
        return "redirect:/departmentList/findAll.do";



}

}
